using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Joystick : MonoBehaviour
{
    public Transform transCircle;//遥杆本身
    public Image imgPoint;//遥杆按钮点
    public Transform ArrowRoot;//外边方向特效
    
    float pointMoveDis = 135;//按钮移动范围
    Vector2 startPos;//遥杆起始位置
    Vector2 defaultPos;//遥杆默认位置
    Vector2 outDir;//输出方向
    
    public Vector3 XYDir => outDir;
    public Vector3 XZDir => new Vector3(outDir.x,0,outDir.y);

    private void Start()
    {
        pointMoveDis = Screen.height * 1.0f / ScreenConfig.ScreenStandardHeight * pointMoveDis;
        defaultPos = transCircle.transform.position;
        ArrowRoot.gameObject.SetActive(false);
    }

    #region Event

    public void OnRangePointerDown(PointerEventData eventData)
    {
        startPos = eventData.position;
        imgPoint.color = new Color(1, 1, 1, 1f);
        transCircle.transform.position = eventData.position;
    }
    public void OnRangePointerUp(PointerEventData eventData)
    {
        transCircle.transform.position = defaultPos;
        imgPoint.color = new Color(1, 1, 1, 0.5f);
        imgPoint.transform.localPosition = Vector2.zero;
        ArrowRoot.gameObject.SetActive(false);
        outDir = Vector2.zero;
    }
    public void OnRangeDrag(PointerEventData eventData)
    {
        var dir = eventData.position - startPos;
        //移动按钮
        if(dir.magnitude > pointMoveDis) 
        {
            var clampDir = Vector2.ClampMagnitude(dir, pointMoveDis);
            imgPoint.transform.position = startPos + clampDir;
        }
        else
            imgPoint.transform.position = eventData.position;
        //设置方向特效
        if(dir != Vector2.zero) 
        {
            ArrowRoot.gameObject.SetActive(true);
            var angle = Vector2.SignedAngle(new Vector2(1, 0), dir);
            ArrowRoot.localEulerAngles = new Vector3(0, 0, angle);
        }

        outDir = dir.normalized;
    }

    #endregion
    
    #region Test
    
    public Transform testObjTrans;
    public float testObjSpeed;
    
    void Update() {
        if(testObjTrans == null)
            return;
        if(XYDir != Vector3.zero) 
        {
            Vector3 pos = XYDir * Time.deltaTime * testObjSpeed;
            testObjTrans.position += pos;
        }
    }
    
    #endregion
}

public static class ScreenConfig 
{
    public const int ScreenStandardWidth = 2160;
    public const int ScreenStandardHeight = 1080;
}